import {useCallback, useRef} from "react";
import {View} from "@tarojs/components";
import styles from "./index.module.scss";

interface Props{
  onDrag: (distance: number)=>void;
  onDragEnd: () => void;
}

export function Drag(props: Props){

  const startY = useRef<number>(0);
  const isDragging = useRef(false);

  const handleTouchStart = useCallback((event: any) => {
    isDragging.current = true;
    startY.current = event.touches[0].pageY;
  }, []);

  const handleTouchMove = useCallback((event: any) => {
    if(!isDragging.current) return;
    props.onDrag(event.touches[0].pageY - startY.current);
  }, [props]);

  const handleTouchEnd = useCallback(()=>{
    if(!isDragging.current) return;
    isDragging.current = false;
    props.onDragEnd();
  }, [props]);

  return (
    <View
      className={styles.dragArea}
      catchMove
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    />
  );
}
